package xin.tianhui.cloud.weblog.service.impl;

import xin.tianhui.cloud.weblog.model.dto.ArticleTypeResultDTO;
import xin.tianhui.cloud.weblog.model.po.ArticleType;
import xin.tianhui.cloud.weblog.mapper.ArticleTypeMapper;
import xin.tianhui.cloud.weblog.service.IArticleTypeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import static xin.tianhui.cloud.weblog.constant.Constants.MAPPER_ARTICLE_TYPE_ID;

/**
 * <p>
 * 文章类别 服务实现类
 * </p>
 *
 * @author junchen
 * @since 2018-04-07
 */
@Service
@CacheConfig(cacheNames="article_type",keyGenerator="keyGenerator")
public class ArticleTypeServiceImpl extends ServiceImpl<ArticleTypeMapper, ArticleType> implements IArticleTypeService {
	
	@Autowired
	private Mapper mapper;
	
	@Cacheable
	public ArticleTypeResultDTO getArticleType(Integer id) {
		ArticleType articleType = new ArticleType();
		articleType.setId(id);
		QueryWrapper<ArticleType> wrapper = new QueryWrapper<ArticleType>(articleType);
		articleType = baseMapper.selectOne(wrapper);
		return Optional.ofNullable(articleType).map(r->{
			ArticleTypeResultDTO dto = new ArticleTypeResultDTO();
			dto.setBid(r.getId());
			dto.setCode(r.getCode());
			dto.setName(r.getName());
			return dto;
		}).orElse(null);
	}
	
	@Cacheable
	@Override
	public List<ArticleTypeResultDTO> articleType() {
		QueryWrapper<ArticleType> wrapper = new QueryWrapper<>();
		List<ArticleType> list = baseMapper.selectList(wrapper);
		return Optional.ofNullable(list).map(result->{
			List<ArticleTypeResultDTO> dtos = Lists.newArrayList();
			result.forEach(r->{
				ArticleTypeResultDTO type = new ArticleTypeResultDTO();
				mapper.map(r, type,MAPPER_ARTICLE_TYPE_ID);
				dtos.add(type);
			});
			return dtos;
		}).orElse(Collections.emptyList());
	}

}
